package com.cxkj.shop.proc;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import net.wangds.common.processor.AbstractProcessorWithResult;
import net.wangds.precasting.processor.io.InputStreamReadAsStringProcessor;
import net.wangds.utilities.lang.CloseableUtils;
import net.wangds.utilities.lang.StringUtils;

import com.cxkj.shop.model.Message;

public abstract class MessageProc<M extends Message,T> extends AbstractProcessorWithResult<T>{
	
	private String baseUrl="http://114.113.154.5/sms.aspx?action=send";

	private String encoding = "UTF8";
	
	private M msg;
	
	public M getMsg() {
		return msg;
	}

	public void setMsg(M msg) {
		this.msg = msg;
	}

	public String getEncoding() {
		return encoding;
	}

	public void setEncoding(String encoding) {
		this.encoding = encoding;
	}

	public String getBaseUrl() {
		return baseUrl;
	}

	public void setBaseUrl(String baseUrl) {
		this.baseUrl = baseUrl;
	}

	protected URL buildSendUrl(M msg) throws MalformedURLException{
		return new URL(StringUtils.join(this.getBaseUrl(),"&userid="
				, msg.getUserid() , "&account=" , msg.getAccount()
				, "&password=" , msg.getPassword() , "&mobile="
				, msg.getMobile() , "&content=" , msg.buildMessageBody()
				, "&sendTime=" , msg.getSendTime()));
	}

	public T SendMessage(M msg, String encoding) {
		if(StringUtils.isNotBlank(encoding)){
			this.setEncoding(encoding);
		}
		this.setMsg(msg);
		this.process();
		return this.getResult();
	}
	
	private String readStringFromReader(InputStream is){
		InputStreamReadAsStringProcessor<InputStream> proc = new InputStreamReadAsStringProcessor<InputStream>();
		proc.setInputStream(is);
		proc.setEncoding(this.getEncoding());
		proc.process();
		return proc.getResult();
	}
	
	@Override
	protected T execute() {
		T res = null;
		HttpURLConnection con = null;
		InputStream is = null;
		URL url = null;
		try {
			url = buildSendUrl(msg);
			con = (HttpURLConnection) url.openConnection();
			is = con.getInputStream();
			String resp = this.readStringFromReader(is);
			res = this.handleResponseString(resp);
		} catch (MalformedURLException e) {
			this.getLogger().error(e.getLocalizedMessage(),e);
		} catch (IOException e) {
			this.getLogger().error(e.getLocalizedMessage(),e);
		}finally{
			CloseableUtils.close(is);
		}
		return res;
	}
	
	protected abstract T handleResponseString(String resp);

}
